#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : aimix
@File    : video_deduplication.py
@IDE     : PyCharm
@Author  : admin
@Date    : 2025/4/21 14:07
"""
import random
import shutil
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
from core.video.single_video_process_method import *



class VideoDeduplication:
    def __init__(
        self,
        input_files,
        output_path,
        flip_status=False,
        speed_up_status=False,
        extract_frames_status=False,
        add_img_overlay_status=False,
        add_video_overlay_status=False,
        adjust_video_status=False,
        adjust_hsl_status=False,
        adjust_color_balance_status=False,
        **kwargs
    ):
        """
        初始化函数
        :param input_files: 输入文件列表
        :param output_path: 输出路径
        :param flip_status: 是否翻转视频
        :param speed_up_status: 是否加速视频
        :param extract_frames_status: 是否提取视频帧
        :param add_img_overlay_status: 是否添加图片水印
        :param add_video_overlay_status: 是否添加视频水印
        :param adjust_video_status: 是否调整视频
        :param adjust_hsl_status: 是否调整HSL
        :param adjust_color_balance_status: 是否调整色彩平衡
        :param kwargs: 其他参数
        """
        self.input_files = input_files
        self.output_path = output_path
        self.flip_status = flip_status
        self.speed_up_status = speed_up_status
        self.extract_frames_status = extract_frames_status
        self.add_img_overlay_status = add_img_overlay_status
        self.add_video_overlay_status = add_video_overlay_status
        self.adjust_video_status = adjust_video_status
        self.adjust_hsl_status = adjust_hsl_status
        self.adjust_color_balance_status = adjust_color_balance_status
        self.kwargs = kwargs
        self.temp_dir = os.path.join(tempfile.gettempdir(), datetime.now().strftime('%Y-%m-%d'))  # 临时目录
        os.makedirs(self.temp_dir, exist_ok=True)


    def __del__(self):
        for l in os.listdir(self.temp_dir):
            try:
                os.remove(l)
            except Exception as e:
                pass

    def __make_temp_file(self, suffix=".mp4"):
        return tempfile.mktemp(suffix=suffix, dir=self.temp_dir)

    def complete(self, input_file):
        temp_file = self.__make_temp_file()
        shutil.copy(input_file, temp_file)
        print("复制文件成功")
        # 使用临时文件作为中间输出
        current_file = temp_file

        if self.flip_status:
            current_file = flip_video_horizontally(current_file, self.__make_temp_file())
        if self.speed_up_status:
            current_file = speed_up_video_with_audio(
                current_file,
                self.__make_temp_file(),
                random.uniform(
                    self.kwargs.get("speed_up_min", 1.0),
                    self.kwargs.get("speed_up_max", 1.5),
                ),
            )
        if self.extract_frames_status:
            current_file = random_frame_extraction(
                current_file,
                self.__make_temp_file(),
                random.randint(self.kwargs.get("extract_frames_min", 20),
                self.kwargs.get("extract_frames_max", 30)),
            )
        if self.add_img_overlay_status:
            current_file = add_image_overlay_to_video(
                current_file,
                self.kwargs.get("img_overlay_path"),
                self.__make_temp_file(),
                opacity=self.kwargs.get("img_overlay_opacity", 0.5),
                position=self.kwargs.get("img_overlay_position", ("center", "center")),
            )
        if self.add_video_overlay_status:
            current_file = add_video_overlay_to_video(
                current_file,
                self.kwargs.get("video_overlay_path"),
                self.__make_temp_file(),
                opacity=self.kwargs.get("video_overlay_opacity", 0.5),
                position=self.kwargs.get(
                    "video_overlay_position", ("center", "center")
                ),
            )
        if self.adjust_video_status:
            current_file = adjust_video(
                current_file,
                self.__make_temp_file(),
                self.kwargs.get("brightness", 1.0),
                self.kwargs.get("contrast", 1.0),
                self.kwargs.get("saturation", 1.0),
                self.kwargs.get("gamma", 1.0),
            )

        if self.adjust_hsl_status:
            current_file = adjust_hsl(
                current_file,
                self.__make_temp_file(),
                self.kwargs.get("hue_shift", 0),
                self.kwargs.get("saturation_factor", 1.0),
                self.kwargs.get("lightness_factor", 1.0),
            )

        if self.adjust_color_balance_status:
            current_file = adjust_color_balance(
                current_file,
                self.__make_temp_file(),
                self.kwargs.get("shadow_red", 0.0),
                self.kwargs.get("shadow_green", 0.0),
                self.kwargs.get("shadow_blue", 0.0),
                self.kwargs.get("midtones_red", 0.0),
                self.kwargs.get("midtones_green", 0.0),
                self.kwargs.get("midtones_blue", 0.0),
                self.kwargs.get("highlights_red", 0.0),
                self.kwargs.get("highlights_green", 0.0),
                self.kwargs.get("highlights_blue", 0.0),
            )
        shutil.move(current_file, self.output_path)
        return os.path.join(self.output_path, os.path.basename(input_file))

    def run(self):

        with ThreadPoolExecutor(max_workers=5) as executor:
            futures = []
            result = []
            for args in self.input_files:
                futures.append(executor.submit(self.complete, args))
            for future in as_completed(futures):
                future.result()
        return result
